const db = require('../config/database');
const logger = require('../config/logger');

/**
 * 获取系统日志列表
 */
exports.getSystemLogs = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 1000,
      level = '',
      action = '',
      keyword = '',
      start_date = '',
      end_date = ''
    } = req.query;

    const offset = (page - 1) * limit;
    let query = `
      SELECT
        sl.id,
        sl.level,
        sl.action,
        sl.content as details,
        sl.ip_address,
        sl.created_at,
        sl.deleted_at,
        CASE
          WHEN sl.user_type = 'admin' THEN (SELECT username FROM admins WHERE id = sl.user_id)
          WHEN sl.user_type = 'user' THEN (SELECT username FROM users WHERE id = sl.user_id)
          ELSE 'system'
        END as admin_username
      FROM system_logs sl
      WHERE 1=1
    `;

    let countQuery = 'SELECT COUNT(*) as total FROM system_logs WHERE 1=1';
    const params = [];

    // 日志级别筛选
    if (level) {
      query += ' AND sl.level = ?';
      countQuery += ' AND level = ?';
      params.push(level);
    }

    // 操作类型筛选
    if (action) {
      query += ' AND sl.action = ?';
      countQuery += ' AND action = ?';
      params.push(action);
    }

    // 关键字搜索
    if (keyword) {
      query += ' AND sl.content LIKE ?';
      countQuery += ' AND content LIKE ?';
      params.push(`%${keyword}%`);
    }

    // 日期范围筛选
    if (start_date) {
      query += ' AND sl.created_at >= ?';
      countQuery += ' AND created_at >= ?';
      params.push(start_date);
    }

    if (end_date) {
      query += ' AND sl.created_at <= ?';
      countQuery += ' AND created_at <= ?';
      params.push(end_date);
    }

    // 获取总数
    const [countResult] = await db.query(countQuery, params);
    const total = countResult[0].total;

    // 分页查询
    query += ' ORDER BY sl.created_at DESC LIMIT ? OFFSET ?';
    const [logs] = await db.query(query, [...params, parseInt(limit), offset]);

    res.json({
      success: true,
      data: {
        logs,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('获取系统日志失败:', error);
    res.status(500).json({
      success: false,
      message: '获取系统日志失败'
    });
  }
};

/**
 * 获取客户端日志列表
 */
exports.getClientLogs = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 1000,
      level = '',
      user_id = '',
      keyword = '',
      start_date = '',
      end_date = ''
    } = req.query;

    const offset = (page - 1) * limit;
    let query = `
      SELECT
        cl.id,
        cl.user_id,
        cl.client_id,
        cl.level,
        cl.message,
        cl.stack_trace,
        cl.client_time,
        cl.received_at,
        u.username
      FROM client_logs cl
      LEFT JOIN users u ON cl.user_id = u.id
      WHERE 1=1
    `;

    let countQuery = 'SELECT COUNT(*) as total FROM client_logs WHERE 1=1';
    const params = [];

    // 日志级别筛选
    if (level) {
      query += ' AND cl.level = ?';
      countQuery += ' AND level = ?';
      params.push(level);
    }

    // 用户筛选
    if (user_id) {
      query += ' AND cl.user_id = ?';
      countQuery += ' AND user_id = ?';
      params.push(user_id);
    }

    // 关键字搜索
    if (keyword) {
      query += ' AND cl.message LIKE ?';
      countQuery += ' AND message LIKE ?';
      params.push(`%${keyword}%`);
    }

    // 日期范围筛选
    if (start_date) {
      query += ' AND cl.received_at >= ?';
      countQuery += ' AND received_at >= ?';
      params.push(start_date);
    }

    if (end_date) {
      query += ' AND cl.received_at <= ?';
      countQuery += ' AND received_at <= ?';
      params.push(end_date);
    }

    // 获取总数
    const [countResult] = await db.query(countQuery, params);
    const total = countResult[0].total;

    // 分页查询
    query += ' ORDER BY cl.received_at DESC LIMIT ? OFFSET ?';
    const [logs] = await db.query(query, [...params, parseInt(limit), offset]);

    res.json({
      success: true,
      data: {
        logs,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('获取客户端日志失败:', error);
    res.status(500).json({
      success: false,
      message: '获取客户端日志失败'
    });
  }
};

/**
 * 导出系统日志
 */
exports.exportSystemLogs = async (req, res) => {
  try {
    const {
      level = '',
      action = '',
      keyword = '',
      start_date = '',
      end_date = ''
    } = req.query;

    let query = `
      SELECT
        sl.id,
        sl.level,
        sl.action,
        sl.content as details,
        sl.ip_address,
        sl.created_at,
        CASE
          WHEN sl.user_type = 'admin' THEN (SELECT username FROM admins WHERE id = sl.user_id)
          WHEN sl.user_type = 'user' THEN (SELECT username FROM users WHERE id = sl.user_id)
          ELSE 'system'
        END as admin_username
      FROM system_logs sl
      WHERE sl.deleted_at IS NULL
    `;

    const params = [];

    if (level) {
      query += ' AND sl.level = ?';
      params.push(level);
    }

    if (action) {
      query += ' AND sl.action = ?';
      params.push(action);
    }

    if (keyword) {
      query += ' AND sl.content LIKE ?';
      params.push(`%${keyword}%`);
    }

    if (start_date) {
      query += ' AND sl.created_at >= ?';
      params.push(start_date);
    }

    if (end_date) {
      query += ' AND sl.created_at <= ?';
      params.push(end_date);
    }

    query += ' ORDER BY sl.created_at DESC LIMIT 50000'; // 🔥 增加导出数量限制

    const [logs] = await db.query(query, params);

    // 生成CSV
    const csv = [
      ['ID', '级别', '操作', '详情', 'IP地址', '操作人', '时间'].join(','),
      ...logs.map(log => [
        log.id,
        log.level,
        log.action,
        `"${log.details || ''}"`,
        log.ip_address || '',
        log.admin_username || '',
        log.created_at
      ].join(','))
    ].join('\n');

    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename=system_logs_${Date.now()}.csv`);
    res.send('\uFEFF' + csv); // 添加BOM以支持Excel中的中文
  } catch (error) {
    logger.error('导出系统日志失败:', error);
    res.status(500).json({
      success: false,
      message: '导出系统日志失败'
    });
  }
};

/**
 * 🔥 接收客户端上传的日志（带客户端ID）
 */
exports.uploadClientLogs = async (req, res) => {
  try {
    const { logs, clientId } = req.body; // 🔥 接收 clientId
    const userId = req.user.id;

    if (!logs || !Array.isArray(logs) || logs.length === 0) {
      return res.status(400).json({
        success: false,
        message: '日志数据格式错误'
      });
    }

    logger.info(`收到客户端日志上传，用户ID: ${userId}, 客户端ID: ${clientId || '未提供'}, 日志数量: ${logs.length}`);

    // 🔥 批量插入日志（包含 client_id）
    const values = logs.map(log => {
      // 🔥 转换 ISO 时间戳为 MySQL 格式
      let clientTime;
      if (log.timestamp) {
        const date = new Date(log.timestamp);
        clientTime = date.toISOString().slice(0, 19).replace('T', ' ');
      } else {
        const now = new Date();
        clientTime = now.toISOString().slice(0, 19).replace('T', ' ');
      }
      
      return [
        userId,
        clientId || null, // 🔥 客户端ID
        log.level || 'info',
        log.message || '',
        log.stack || null,
        clientTime, // 🔥 MySQL 格式时间
        new Date().toISOString().slice(0, 19).replace('T', ' ') // 🔥 MySQL 格式时间
      ];
    });

    if (values.length > 0) {
      await db.query(
        `INSERT INTO client_logs (user_id, client_id, level, message, stack_trace, client_time, received_at)
         VALUES ?`,
        [values]
      );

      logger.info(`客户端日志保存成功，插入 ${values.length} 条记录`);
    }

    res.json({
      success: true,
      message: `成功上传 ${logs.length} 条日志`
    });
  } catch (error) {
    logger.error('接收客户端日志失败:', error);
    res.status(500).json({
      success: false,
      message: '保存客户端日志失败'
    });
  }
};

/**
 * 导出客户端日志
 */
exports.exportClientLogs = async (req, res) => {
  try {
    const {
      level = '',
      user_id = '',
      keyword = '',
      start_date = '',
      end_date = ''
    } = req.query;

    let query = `
      SELECT
        cl.id,
        cl.user_id,
        cl.client_id,
        cl.level,
        cl.message,
        cl.stack_trace,
        cl.client_time,
        cl.received_at,
        u.username
      FROM client_logs cl
      LEFT JOIN users u ON cl.user_id = u.id
      WHERE 1=1
    `;

    const params = [];

    if (level) {
      query += ' AND cl.level = ?';
      params.push(level);
    }

    if (user_id) {
      query += ' AND cl.user_id = ?';
      params.push(user_id);
    }

    if (keyword) {
      query += ' AND cl.message LIKE ?';
      params.push(`%${keyword}%`);
    }

    if (start_date) {
      query += ' AND cl.received_at >= ?';
      params.push(start_date);
    }

    if (end_date) {
      query += ' AND cl.received_at <= ?';
      params.push(end_date);
    }

    query += ' ORDER BY cl.received_at DESC LIMIT 50000'; // 🔥 增加导出数量限制

    const [logs] = await db.query(query, params);

    // 生成CSV
    const csv = [
      ['ID', '级别', '消息', '堆栈跟踪', '客户端时间', '接收时间', '用户', '客户端ID'].join(','),
      ...logs.map(log => [
        log.id,
        log.level,
        `"${log.message || ''}"`,
        `"${log.stack_trace || ''}"`,
        log.client_time,
        log.received_at,
        log.username || '',
        log.client_id || ''
      ].join(','))
    ].join('\n');

    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename=client_logs_${Date.now()}.csv`);
    res.send('\uFEFF' + csv);
  } catch (error) {
    logger.error('导出客户端日志失败:', error);
    res.status(500).json({
      success: false,
      message: '导出客户端日志失败'
    });
  }
};

module.exports = exports;
